<template>
    <div class="task">
        <div class="tabHeader">
            <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item,index) in editableTabs" :key="item.id" :name="item.name" :label="item.name">
                    <span slot="label">
                        <el-popover placement="bottom-start"
                            popper-class='custom'>
                            <span slot="reference">{{item.name}}</span>
                            <div class="secondGroup">
                                <div class="item-card" v-for="(i,index) in secondGroupInfo.typeCountData" 
                                    :key="i.optionValue" 
                                    :class="{active:activeValue === i.optionValue}"
                                    @click="handleSecondGroup(i,secondGroupInfo,item)">
                                    <i class="iconfont icon-caiyouduo_hemaixiangqing-fanganxiangqing icon" style="font-size:18px"></i>
                                    <span class="groupName">{{i.optionName}}</span>
                                    <span class="groupName" style="margin-left:8px">{{i.optionNum}}</span>
                                </div>
                            </div>
                        </el-popover>
                    </span>
                </el-tab-pane>
            </el-tabs>

            <div class="setBtn">
                <my-button type='primary' plain size='mini' class='el-icon-circle-check'
                    @btnClick='$refs.saveScheme.showDialog()'>
                    保存当前
                </my-button>
                <my-button type='primary' size='mini' class='el-icon-edit-outline'
                    @btnClick='$refs.scheme.drawerOpen()'>
                    筛选方案
                </my-button>
            </div>
        </div>

        <!-- 动态表单 -->
        <dynamic-form :formDataList='formDataList' @getFormData='getFormData' ref='dynamicForm'></dynamic-form>

        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-upload2" plain @click='getMissionExport'
                        :disabled='computedTotal'>导出
                    </el-button>
                    <el-button type="primary" size="mini" icon="el-icon-s-operation" :disabled='isBatchCheck'
                        @click='batch'>
                        批量修改
                    </el-button>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                        @click="$router.push('/productionManagement/task/customEvent')">自定义事件</el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <my-button type="primary" size="mini" icon="el-icon-setting" @btnClick="cardHandle('mission,workOrder')">
                        移动端卡片设置
                    </my-button>

                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 批量修改 -->
        <batch-modify ref='batch' @confirmModify='confirmModify'></batch-modify>

        <!-- 移动端卡片设置 -->
        <el-drawer title="卡片设置" :visible.sync="cardSetDrawer" direction="rtl" size='450px' custom-class='card'
            @close='cardSetClose'>
            <div class='cardSet' v-loading="cardSetLoading" element-loading-text="加载中" 
                element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
               <el-form :model="cardSetForm" :rules="cardSetRules" ref="cardSetForm" label-width="100px" size="mini"
                >
                    <el-form-item label="标题" prop="titleValues" placeholder='请选择'>
                        <el-select v-model="cardSetForm.titleValues" multiple filterable>
                            <el-option
                                v-for="(item,index) in titleValuesOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="封面" prop='coverValue'>
                        <el-select v-model="cardSetForm.coverValue" filterable>
                            <el-option
                                v-for="(item,index) in coverValueOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="展示字段" prop="columnValues" placeholder='请选择' style='overflow:hidden'>
                        <el-select v-model="cardSetForm.columnValues" multiple filterable @change='fieldChange'
                            >
                            <el-option
                                v-for="(item,index) in columnValuesOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <div class='checkBox'>
                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                            <el-checkbox-group v-model="checkedField" @change="handleCheckedCitiesChange">
                                <div v-for="(i,index) in fields" :key="index" class="group_div">
                                    <el-checkbox :label="i" style="width:100%"></el-checkbox>
                                    <!-- <span class="iconfont icon-row key"></span> -->
                                </div>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="operate" style="textAlign:center">
                <el-button size="mini" style="padding:7px 35px" @click='cardSetDrawer = false'>取 消</el-button>
                <el-button type="primary" size="mini"style="padding:7px 35px" @click='saveCardSet({belongModule:1})'>确 定</el-button>
            </div>
        </el-drawer>

        <!-- 表格 -->
        <table-list :tableGroup='tableGroup' @getCheckedId='getCheckedId'
            :searchForm='searchForm' @getTotal='getTotal' @updateList='updateList' 
            @getSecondGroupInfo="getSecondGroupInfo" ref='tableList'>
        </table-list>

        <!-- 保存当前 -->
        <save-current ref="saveScheme" @getList='getList' :editableTabs='allTabs' @fromOutDrawerClose='fromOutDrawerClose'></save-current>

        <!-- 筛选方案--创建方案 -->
        <operate-scheme ref="scheme" :editableTabs='allTabs' @getList='getList' @fromOutDrawerClose='fromOutDrawerClose'
            @lastData='lastData'></operate-scheme>
    </div>
</template>

<script>
    import {
        missionEdit,
        screenPlanList
    } from '@/api/produceController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import {h5CardSet} from "@/mixin"
    import tableList from './tableList.vue'
    import dynamicForm from '@/components/dynamicForm'
    import saveCurrent from './saveCurrent.vue'
    import operateScheme from './operateScheme.vue'
    import batchModify from './batchModify.vue'
    export default {
        data() {
            return {
                editableTabsValue: '',
                editableTabs: [],
                allTabs:[],
                fromSavaCurrent:0,
                isMounted:'',
                secondGroupInfo:[],
                activeValue:'all',
                enumState:{
                    0:'未开始',
                    1:'执行中',
                    2:'已结束',
                    3:'已取消'
                },
                enumDisState:{
                    '-1':'全部',
                    0:'已分配',
                    1:'未分配'
                },
                enumDynamicType:{
                    1:'今天',
                    2:'昨天',
                    3:'本周',
                    4:'上周',
                    5:'本月',
                    6:'上月',
                    7:'近三月',
                },
                customFieldMap:{},
                isCollapse: false,
                formDataList: {
                    formGroup: [{
                            label: 'workOrderCode',
                            name: '工单编号',
                            prop: '',
                            placeholder: '请输入工单编号',
                            key: 'srk'
                        },
                        {
                            label: 'processCode',
                            name: '工序编号',
                            prop: '',
                            placeholder: '请输入工序编号',
                            key: 'srk'
                        },
                        {
                            label: 'processName',
                            name: '工序名称',
                            prop: '',
                            placeholder: '请输入工序名称',
                            key: 'srk'
                        },
                        {
                            label: ['startTime', 'endTime'],
                            name: '计划时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: ['actualStartTime', 'actualEndTime'],
                            name: '实际时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: 'productCode',
                            name: '产品编号',
                            prop: '',
                            placeholder: '请输入产品编号',
                            key: 'srk'
                        },
                        {
                            label: 'productName',
                            name: '产品名称',
                            prop: '',
                            placeholder: '请输入产品名称',
                            key: 'srk'
                        },
                        {
                            label: 'productSpecification',
                            name: '产品规格',
                            prop: '',
                            placeholder: '请输入产品规格',
                            key: 'srk'
                        },
                        {
                            label: 'processState',
                            name: '工序状态',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: [],
                                isRadio: false,
                                options: [{
                                        value: 0,
                                        label: '未开始'
                                    },
                                    {
                                        value: 1,
                                        label: '执行中'
                                    },
                                    {
                                        value: 2,
                                        label: '已结束'
                                    },
                                ]
                            }
                        },
                        {
                            label: 'distributionState',
                            name: '分配状态',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            node: {
                                default: '',
                                isRadio: true,
                                options: [{
                                        value: -1,
                                        label: '全部'
                                    },
                                    {
                                        value: 0,
                                        label: '未分配'
                                    },
                                    {
                                        value: 1,
                                        label: '已分配'
                                    },
                                ]
                            }
                        },
                        {
                            label: 'distribution',
                            name: '分配列表',
                            placeholder: '请选择',
                            key: 'sci',
                            dataUrl: {
                                url: '/user/distributionUserList',
                                value: 'id'
                            }
                        },
                    ],
                    searchForm: {
                        workOrderCode: '',
                        processCode: '',
                        processName: '',
                        startTime: '',
                        endTime: '',
                        actualStartTime: '',
                        actualEndTime: '',
                        productCode: '',
                        productName: '',
                        productSpecification: '',
                        processState: [],
                        distributionState: '',
                    },
                    formSet: true,
                    type:'mission'
                },
                searchForm:{
                    customFieldMap:{},
                    searchOther:{},
                    page:1,
                    limit:10,
                },
                tableGroup: [],
                disposeGroup: [],
                tableTotal:0,
                batchIds:''
            }
        },
        components: {
            dynamicForm,
            tableList,
            saveCurrent,
            operateScheme,
            batchModify
        },
        mixins:[h5CardSet],
        mounted(){
            if (this.$store.state.router === this.$route.path) {
                this.searchForm.page = this.$store.state.page || 1;
            }
            this.isMounted = 'mounted'
            this.getProductColumns({
                type: 'mission'
            })
            this.getScreenPlanList({type:1})
        },
        computed:{
            isBatchCheck(){
                return this.batchIds.length <= 0
            },
            computedTotal(){
                return this.tableTotal <= 0
            }
        },
        watch:{
            tableTotal(total){
                //当表格数据为空时 列配置和表头无自定义字段信息
                if(total <= 0) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        methods: {
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                            index:'80',
                            workOrderCode:'155',
                            productCode:'150',
                            processCode:'155',
                            productName:'130',
                            productSpecification:'70',
                            distributionName:'150',
                            processPermissions:'80',
                            rate:'90',
                            planedNumber:'80',
                            goodProductNumber:'70',
                            badProductNumber:'70',
                            processState:'70',
                            startTime:'140',
                            endTime:'140',
                            actualStartTime:'140',
                            actualEndTime:'140'
                        }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'mission',
                    configureList
                }).then(()=>{
                    this.$refs.tableList.updateTable()
                })
            },
            getTotal(total){
                this.tableTotal = total
            },
            //编辑
            getMissionEdit(data) {
                missionEdit(data).then(res => {
                    if (res.code == 200) {
                        let state = ''
                        if(res.data.successNum && !res.data.failNum){
                            state = 'success'
                        }else if(res.data.failNum && !res.data.successNum){
                            state = 'error'
                        }else{
                            state = 'warning'
                        }
                        this.$refs.tableList.clearSelection()
                        this.fromOutDrawerClose()
                        this.$refs.batch.isOpen(false)
                        this.utils.showMsg(`成功${res.data.successNum}条,失败${res.data.failNum}条`, state)
                    }
                })
            },
            updateList(){
                this.fromOutDrawerClose()
            },
            //批量修改
            batch(){
                this.$refs.batch.isOpen(true)
            },
            //确认修改
            confirmModify(form){
                form.ids = this.batchIds
                this.getMissionEdit(form)
            },
            //点击查询获取表单数据
            getFormData(val) {
                this.searchForm.page = 1
                this.handleFormData(val)
                this.$refs.tableList.getMissionList(this.searchForm)
            },
            //处理非筛选方案表单项自定义和非自定义字段数据
            handleFormData(val){
                this.searchForm.searchOther = {}
                this.customFieldMap = {}
                for (const key in val) {
                    /**
                     * 自定义字段表单数据放在searchOther中的customFieldMap对象中
                     * 其中计数器--日期选择器--多选框以 `[自定义字段id]:'arr[0],arr[1]'` 形式传给后端
                     * 其它类型表单项以`[自定义字段id]:'value' 形式传给后端
                     */
                    if (!isNaN(parseFloat(key)) && isFinite(key)) { 
                        let str = ''
                        if(Array.isArray(val[key])){
                            val[key].forEach(k => str += k + ',')
                            if(str.length > 0) str = str.substr(0,str.length - 1)
                        }
                        this.customFieldMap[key] = Array.isArray(val[key]) ? str : val[key]
                        this.searchForm.searchOther.customFieldMap = this.customFieldMap
                    }else{ //非自定义字段表单数据放在searchOther对象中
                        this.searchForm.searchOther[key] = val[key]
                    }
                }
                //点击查询按钮时需要将筛选方案表单项数据和非筛选方案表单项数据同时接收，做合并查询
                if(this.editableTabs.length){ 
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.handleSchemeData(findTab)
                }
            },
            //获取筛选方案列表
            getList(payload){
                this.fromSavaCurrent = payload == undefined || payload.length
                this.getScreenPlanList({type:1},payload == undefined || {delIndex:payload.delIndex,name:payload.name})
            },
            handleTabClick(tab){
                this.searchForm.page = 1;
                this.activeValue = 'all'
                const target = this.editableTabs.find(i => i.name == tab.label)                
                this.schemeClick(target)
            },
            //获取二级分组信息
            getSecondGroupInfo(payload){
                const {typeCountData} = payload
                typeCountData.unshift({
                    optionName: "全部",
                    optionValue: "all"
                })
                this.secondGroupInfo = payload
            },
            //处理二级分组
            handleSecondGroup(group,secondGroupInfo){
                const {optionValue} = group
                const {key} = secondGroupInfo
                this.activeValue = optionValue
                this.searchForm.page = 1
                this.searchForm.secondSearchCondition = {
                    conditionName:optionValue === 'all' ? undefined : key,
                    conditionValue:optionValue === 'all' ? undefined : optionValue
                }
                this.$refs.tableList.getMissionList(this.searchForm)
            },
            //筛选方案列表
            getScreenPlanList(data,p) {
                screenPlanList(data,p).then(res => {
                    if (res.code == 200) {
                        this.editableTabs = res.data.filter(i => i.isValid)
                        this.allTabs = res.data
                        if(!res.data.length) return //初始化进入页面时若无筛选方案不调用列表接口
                        /**
                         *  创建第一条筛选方案时tabs下划线默认选中，
                            当超过一条时，点击到第n个筛选方案，此时打开drawer再关闭tabs下划线默认为第n个
                         */
                        if(res.data.length && res.data.length == 1) this.editableTabsValue = res.data[0].name
                        /**
                         * 当选中第n个tabs标签页，此时打开筛选方案删除当前第n条数据时，tabs下划线默认向前移动一位
                         */
                        if(p != undefined && p.delIndex && p.name == this.editableTabsValue) {
                            this.editableTabsValue = res.data[p.delIndex - 1].name
                        }
                        /**
                         * 保存当前 || 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         * isMounted : 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         *             当创建第二条以上时将isMounted = '' 不需要再调用列表接口
                         */
                        if(this.fromSavaCurrent === 1 || this.isMounted == 'mounted') {
                            if (this.$store.state.tab && this.$store.state.router === this.$route.path) {
                                this.schemeClick(JSON.parse(this.$store.state.tab));
                            } else {
                                this.schemeClick(res.data[0]);
                            } 
                        } 
                    }
                })
            },
            //关闭筛选方案列表
            fromOutDrawerClose(){
                if(this.editableTabs.length){ //当没有筛选方案时不需要调用列表接口
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.schemeClick(findTab)
                }
            },
            //删除筛选方案最后一条数据时
            lastData(){
                let payload = {
                    searchOther:{
                        processState:[-1]
                    },
                    page:1,
                    limit:10,
                }
                this.$refs.tableList.getMissionList(payload)
            },
            //tabs标签页--popover框
            schemeClick(item){
                this.$store.commit('setRouter', this.$route.path);
                this.$store.commit('setTab', JSON.stringify(item));
                this.searchForm = { //多个筛选方案互相切换先置空
                    customFieldMap:{},
                    searchOther:{},
                    screenPlanId:item.id,
                    page:this.searchForm.page,
                    limit:10,
                }
                this.isMounted = ''
                /**
                 * getValue 这个方法单独获取已填写的非筛选方案表单项的数据
                 * 若通过selectData获取会触发'getFormData'导致每次点击筛选方案tabs标签重复调用列表接口
                 */
                let formDataPayload = this.$refs.dynamicForm.getValue()
                this.handleSchemeData(item)
                this.handleFormData(formDataPayload)
                this.$refs.tableList.getMissionList(this.searchForm)
            },
            //处理筛选方案表单项自定义和非自定义字段数据
            handleSchemeData(item){
                let screenCondition = []
                let payload = {}
                screenCondition = JSON.parse(item.screenCondition).configData
                screenCondition.forEach(i => {
                    if(i.fieldId == 'plan' || i.fieldId == 'actual'){
                        payload[i.fieldId == 'plan' ? 'startTime' : 'actualStartTime'] = i.fieldValue[0]
                        payload[i.fieldId == 'plan' ? 'endTime' : 'actualEndTime'] = i.fieldValue[1]
                        payload['endTime'] = i.fieldValue[1]
                    }else if(i.type != undefined && i.type != 'selectRadio' && i.type != 'ipt'){
                        let str = ''
                        i.fieldValue.forEach(k =>{
                            str += k + ','
                        })
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                        payload[i.fieldId] = str
                    }else if(i.fieldId == 'distributionsList'){
                        let str = ''
                        i.fieldValue.forEach(i =>{
                            str += i.value + '，' 
                        })
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                        payload[i.fieldId] = str
                    }else{
                        payload[i.fieldId] = i.fieldValue
                    }
                })
                this.editableTabsValue = item.name
                for (const key in payload) {
                    if (!isNaN(parseFloat(key)) && isFinite(key)) {
                        this.searchForm.customFieldMap[key] = payload[key]
                    }else{
                        this.searchForm[key] = payload[key]
                    }
                }
            },
            //获取勾选中表格的id
            getCheckedId(ids) {
                this.batchIds = ids
            },
            //任务导出
            getMissionExport() {
                let enumProps = {
                    processState:{
                        0:'未开始',
                        1:'执行中',
                        2:'已结束',
                        3:'已取消'
                    }
                }
                this.$refs.tableList.getTableData(
                    this.searchForm,
                    '/produce/mission_list',
                    '任务' + new Date().dateFormat('yyyyMMddhhmmss'),
                    1,
                    enumProps
                )
            },
        },
    }
</script>

<style lang="less" scoped>
    .task {
        overflow: auto;

        .tabHeader {
            height: 44px;
            background-color: rgb(250, 250, 250);
            padding-left: 10px;

            .el-tabs {
                float: left;
                max-width: 1000px;
            }

            /deep/ .el-tabs__header {
                margin: 0;
                padding-top: 4px;
            }

            /deep/ .el-tabs__nav-wrap::after {
                opacity: 0;
            }

            /deep/ .el-tabs__item {
                padding: 0 10px;
            }

            /deep/ .el-tabs__item:first-child {
                padding-left: 0px;
            }
            /deep/ .el-tabs__item:last-child {
                padding-right: 0px;
            }


            /deep/ .el-tabs__nav {
                height: 40px;
            }

            /deep/ .el-tabs__nav-next, /deep/ .el-tabs__nav-prev{
                line-height: 38px;
            }

            .setBtn {
                float: right;
                margin-top: 8px;
                margin-right: 20px;
            }
        }

        /deep/ .el-drawer.rtl.card{
            .el-drawer__body{
                padding: 0;
                .operate{
                    width: 100%;
                    height: 40px;
                }
            }
        }

        .cardSet{
            flex: 1;
            overflow-y: auto;
            padding: 20px 20px 0 20px;

            .checkBox{
                padding: 18px 20px;
                border: 1px solid #e5e5e5;
                border-radius: 4px;
                max-height: 450px;
                overflow-y: auto;

                .el-checkbox-group{
                    display: flex;
                    flex-wrap: wrap;
                    .el-checkbox{
                        width: 50%;
                    }

                    .group_div {
                        display: flex;
                        height: 30px;
                        align-items: center;
                        justify-content: space-between;
                        width: 100%;

                        .key {
                            color: #409EFF;
                        }
                    }

                    .iconfont.icon-row.key{
                        font-size: 12px;
                    }
                }
            }

            .el-select{
                width: 100%;
                /deep/ .el-tag.el-tag--info{
                    transition: none;
                }
                /deep/ .el-select__tags{
                    top: 3px;
                    transform: none;
                }
            }
        }

        /deep/ th.el-table__cell.gutter {
            background-color: #fafafa;
        }

        /deep/ .el-dialog__body {
            padding: 10px 50px 10px 30px;

        }
    }
</style>